// pages/home/home.js
import request from '../../utils/network.js'
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    spinShow: true,
    showModal: false,
    active: 0,
    counter: 0,
    price: 0,
    scrolltop: 0,
    categories: [],
    allGoods: [],
    goodsList: [{
      name: '',
      info: 0,
      goods: [],
      countList: [],
    }],
    currentCategory: 0

  },
  /**
   * 去授权登录
   */
  submit() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
    this.setData({
      showModal: false
    })
  },
  /**
   * 取消授权登录弹框
   */
  cancel() {
    this.setData({
      showModal: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //获取商品类别
    this.getgGoodCategories()
  },
  //获取商品类别categories
  getgGoodCategories() {
    //获取本地token
    var token = wx.getStorageSync('token')
    //调用封装网络工具
    request({
      url: 'https://api.it120.cc/kehuafu/shop/goods/category/all',
      data: {
        token: token
      }
    }).then(res => {
      this.setData({
        categories: res.data.data
      })
      this.getgGoods(0) //获取全商品
    }).catch(err => {
      console.log(err)
    });
  },
  //获取全商品
  getgGoods(categoryId) {
    if (categoryId == 0) {
      categoryId = ""
    }
    request({
      url: 'https://api.it120.cc/kehuafu/shop/goods/list',
      data: {
        categoryId: categoryId
      }
    }).then(res => {
      this.setData({
        goods: res.data.data
      })
      console.log("类别：", this.data.categories)
      console.log("全商品：", this.data.goods)
      //对商品类别对的商品进行区分
      var goodsList = []
      var info = []
      for (var i = 0; i < this.data.categories.length; i++) {
        var goods = []
        var countList = []
        info.push(0)
        for (var j = 0; j < this.data.goods.length; j++) {
          if (this.data.goods[j].categoryId == this.data.categories[i].id) {
            goods.push(this.data.goods[j])
            countList.push(0)
          }
        }
        goodsList.push({
          name: this.data.categories[i].name,
          info: 0,
          goods: goods,
          countList: countList
        })
      }
      this.setData({
        [`goodsList`]: goodsList,
        spinShow: false,
        info: info
      })
    }).catch(err => {
      console.log(err)
    })
  },
  //左边商品类别切换
  tabClick(event) {
    //console.log(event)
    //1、取出index
    const index = event.detail.index;

    //2、设置currentType
    this.setData({
      currentCategory: index,
      //currentType: types[index],
      scrolltop: 0,
      currentIndex: index
    })
  },
  addClick(ev) {
    //console.log("-------", ev)
    const count = this.data.counter + 1
    const price = parseFloat((Math.round(ev.detail.price * 100) / 100 + this.data.price).toFixed(2))
    //console.log("++++++++", ev)
    //当前的item是第几个
    const index = ev.currentTarget.dataset.index
    //改变当前item对应list数组的值
    var goodsList = this.data.goodsList
    var currentCategory = this.data.currentCategory
    var list = "goodsList.[" + currentCategory + "].countList[" + index + "]"
    var info = "goodsList.[" + currentCategory + "].info"
    this.setData({
      [list]: ev.detail.count
    })
    const countList = this.data.goodsList[this.data.currentCategory].countList;
    var sum = 0;
    for (var i = 0; i < countList.length; i++) {
      if (countList[i] != 0) {
        sum += countList[i]
      }
    }
    this.setData({
      counter: count,
      price: price,
      [info]: sum
    })
    console.log(this.data.info)
  },
  desClick(ev) {
    //console.log("-------", ev)
    const count = this.data.counter - 1
    const price = parseFloat((this.data.price - Math.round(ev.detail.price * 100) / 100).toFixed(2))
    //console.log("-------", price)
    //当前的item是第几个
    const index = ev.currentTarget.dataset.index
    //改变当前item对应list数组的值
    //console.log("-------", ev.detail.count)
    var goodsList = this.data.goodsList
    var currentCategory = this.data.currentCategory
    var list = "goodsList.[" + currentCategory + "].countList[" + index + "]"
    var info = "goodsList.[" + currentCategory + "].info"
    this.setData({
      [list]: ev.detail.count
    })
    const countList = this.data.goodsList[this.data.currentCategory].countList;
    var sum = 0;
    for (var i = 0; i < countList.length; i++) {
      if (countList[i] != 0) {
        sum += countList[i]
      }
    }
    this.setData({
      counter: count,
      price: price,
      [info]: sum
    })
  },
  //选好了
  selectedFinish() {
    console.log("检测token状态")
    if (this.data.counter == 0) {
      wx.showToast({
        title: '还没选哦~',
      })
      return
    }
    //获取本地token
    var token = wx.getStorageSync('token')
    if (token != '') {
      this.checkToken(token)
    } else {
      //弹出一个对话框，说明要登录才能下单购物
      this.setData({
        showModal: true
      })
    }
  },
  //检测token状态
  checkToken(token) {
    var that = this
    wx.request({
      url: 'https://api.it120.cc/kehuafu/user/check-token',
      data: {
        token: token
      },
      success(res) {
        console.log("Token是否有效：", res.data.msg)
        if (res.data.msg == 'success') {
          if (that.data.counter != 0) {
            //采用全局数据传参，原因是传递的json数据数据太长，跳转传递有限制
            app.globalData.goodsList = that.data.goodsList
            wx.navigateTo({
              url: '/pages/order/order?counter=' + that.data.counter + '&price=' + that.data.price,
              success: function(res) {},
              fail: function(res) {},
              complete: function(res) {},
            })
          } else {
            wx.showToast({
              title: '还没选哦~',
            })
          }
        }
      }
    })
  },
  //点击右边进入我的订单
  clickRight() {
    console.log("检测token状态")
    var token = wx.getStorageSync('token')
    if (token != '') {
      wx.navigateTo({
        url: '/pages/mine/mine',
      })
    } else {
      //弹出一个对话框，说明要登录才能下单购物
      this.setData({
        showModal: true
      })
    }
  },
  //点击左边选择店铺
  clickLeft() {
    console.log("选择店铺")
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    title: 'MC便利店'
    path: 'pages/welcome/index'
    imageUrl: '../../images/logo.png'
  }
})